 package com.leyikao.util;
 
 import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
 public class UploadUtil
 {
   private static UploadUtil uploadUtil;
   private static final String BOUNDARY = UUID.randomUUID().toString();
   private static final String PREFIX = "--";
   private static final String LINE_END = "\r\n";
   private static final String CONTENT_TYPE = "multipart/form-data";
   private static int readTimeOut = 10000;
   private static int connectTimeout = 10000;
 
   private static int requestTime = 0;
   private static final String CHARSET = "utf-8";
   public static final int UPLOAD_SUCCESS_CODE = 1;
   public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;
   public static final int UPLOAD_SERVER_ERROR_CODE = 3;
   protected static final int WHAT_TO_UPLOAD = 1;
   protected static final int WHAT_UPLOAD_DONE = 2;
   private OnUploadProcessListener onUploadProcessListener;
 
   public static UploadUtil getInstance()
   {
     if (uploadUtil == null) {
       uploadUtil = new UploadUtil();
     }
     return uploadUtil;
   }
 
   public void uploadFile(String filePath, String fileKey, String RequestURL, Map<String, String> param)
   {
     if (filePath == null) {
       sendMessage(2, "文件不存在");
       return;
     }
     try {
       File file = new File(filePath);
       uploadFile(file, fileKey, RequestURL, param);
     } catch (Exception e) {
       sendMessage(2, "文件不存在");
       e.printStackTrace();
       return;
     }
   }
 
   public void uploadFile(final File file, final String fileKey, final String RequestURL, final Map<String, String> param)
   {
     if ((file == null) || (!file.exists())) {
       sendMessage(2, "文件不存在");
       return;
     }
 
     new Thread(new Runnable()
     {
       public void run() {
         UploadUtil.toUploadFile(file, fileKey, RequestURL, param);
       }
     }).start();
   }
 
   public static String toUploadFile(File file, String fileKey, String RequestURL, Map<String, String> param)
   {
     String result = null;
     requestTime = 0;
 
     long requestTime = System.currentTimeMillis();
     long responseTime = 0L;
     try
     {
       URL url = new URL(RequestURL);
       HttpURLConnection conn = (HttpURLConnection)url.openConnection();
       conn.setReadTimeout(readTimeOut);
       conn.setConnectTimeout(connectTimeout);
       conn.setDoInput(true);
       conn.setDoOutput(true);
       conn.setUseCaches(false);
       conn.setRequestMethod("POST");
       conn.setRequestProperty("Charset", "utf-8");
       conn.setRequestProperty("connection", "keep-alive");
       conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" +  BOUNDARY);
 
       DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
       StringBuffer sb = null;
       String params = "";
 
       if ((param != null) && (param.size() > 0)) {
         Iterator it = param.keySet().iterator();
         while (it.hasNext()) {
           sb = null;
           sb = new StringBuffer();
           String key = (String)it.next();
           String value = (String)param.get(key);
           sb.append("--").append(BOUNDARY).append("\r\n");
           sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append("\r\n").append("\r\n");
           sb.append(value).append("\r\n");
           params = sb.toString();
 
           dos.write(params.getBytes());
         }
 
       }
 
       sb = null;
       params = null;
       sb = new StringBuffer();
 
       sb.append("--").append(BOUNDARY).append("\r\n");
       sb.append("Content-Disposition:form-data; name=\"" + fileKey + "\"; filename=\"" + file.getName() + "\"" + "\r\n");
       sb.append("Content-Type:image/png\r\n");
 
       sb.append("\r\n");
       params = sb.toString();
       sb = null;
 
       dos.write(params.getBytes());
 
       InputStream is = new FileInputStream(file);
 
       byte[] bytes = new byte[1024];
       int len = 0;
       int curLen = 0;
       while ((len = is.read(bytes)) != -1) {
         curLen += len;
         dos.write(bytes, 0, len);
       }
 
       is.close();
 
       dos.write("\r\n".getBytes());
       byte[] end_data = ("--" + BOUNDARY + "--" + "\r\n")
         .getBytes();
       dos.write(end_data);
       dos.flush();
 
       int res = conn.getResponseCode();
       responseTime = System.currentTimeMillis();
       requestTime = (int)((responseTime - requestTime) / 1000L);
 
       if (res == 200)
       {
         InputStream input = conn.getInputStream();
         StringBuffer sb1 = new StringBuffer();
         int ss;
         while ((ss = input.read()) != -1)
         {
           //int ss;
           sb1.append((char)ss);
         }
         result = sb1.toString();
         System.out.println(result);
 
         return result;
       }
 
       return "上传失败：code=" + res;
     }
     catch (MalformedURLException e)
     {
       e.printStackTrace();
       return "上传失败：error=" + e.getMessage();
     }
     catch (IOException e) {
       e.printStackTrace();
       return "上传失败：error=" + e.getMessage();
     }
   }
 
   public static File filerename(MultipartFile picFile,HttpServletRequest request) {
	   File file =null;
		try{
			// 构建文件保存的目录
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMM");
	        String logoPathDir = "/upload/" + dateformat.format(new Date());
	        // 得到文件保存目录的真实路径
	        String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir).replaceAll("\\\\", "/");
	        // 根据真实路径创建目录
	        File logoSaveFile = new File(logoRealPathDir);
	        if (!logoSaveFile.exists())
	            logoSaveFile.mkdirs();

	        // 文件后缀
	        String suffix = picFile.getOriginalFilename().substring(
	        		picFile.getOriginalFilename().lastIndexOf("."));
	        // 文件名=上传文件名+年月日时分秒
	        SimpleDateFormat dat = new SimpleDateFormat("yyyyMMddHHmmss");
	        String strFileName = picFile.getOriginalFilename() + "_" + dat.format(new Date()) + suffix;
			String strRealFileName = logoRealPathDir + "/" + strFileName;
			file = new File(strRealFileName);
			picFile.transferTo(file);
		}catch(Exception e){
			e.printStackTrace();
		}
		return file;
	}
 
   private void sendMessage(int responseCode, String responseMessage)
   {
     this.onUploadProcessListener.onUploadDone(responseCode, responseMessage);
   }
 
   public void setOnUploadProcessListener(OnUploadProcessListener onUploadProcessListener)
   {
     this.onUploadProcessListener = onUploadProcessListener;
   }
 
   public int getReadTimeOut() {
     return readTimeOut;
   }
 
   public void setReadTimeOut(int readTimeOut) {
     readTimeOut = readTimeOut;
   }
 
   public int getConnectTimeout() {
     return connectTimeout;
   }
 
   public void setConnectTimeout(int connectTimeout) {
     connectTimeout = connectTimeout;
   }
 
   public static int getRequestTime()
   {
     return requestTime;
   }
 
   public static abstract interface OnUploadProcessListener
   {
     public abstract void onUploadDone(int paramInt, String paramString);
 
     public abstract void onUploadProcess(int paramInt);
 
     public abstract void initUpload(int paramInt);
   }
 
   public static abstract interface uploadProcessListener
   {
   }
 }

